/**
 * 簿记管理
 * @author zhangxinyue(2021-02-09)
 */
import accounting from 'accounting';
import { message } from 'antd';
import moment from 'moment';

import api from '../../api';
import typeConfig from '../../comps/business/tradingDirect/config';
import config from '../../comps/business/tradingMarket/config';
import findKeyword from '../../routes/PortfolioMnt/BookkeepingMnt/findKeyword';
import typeOfTradeX from '../../routes/PortfolioMnt/BookkeepingMnt/typeOfTradeX.js';
import delegationTypeData from '../../utils/enumeratedValues/delegationTypeData';
import { fixedNum } from '../../utils/utils';

export default {
  namespace: 'bookkeepingMntM',
  state: {},
  effects: {
    // 获取上传历史记录
    *getUploadHistory({ payload, callback }, { call }) {
      try {
        const res = yield call(api.bookkeepingMnt.getUploadHistory, payload);
        if (res?.code === 0) {
          callback({
            pageInfo: {
              total: res.data.pageInfo.total,
              currentPage: res.data.pageInfo.currentPage,
              pageSize: res.data.pageInfo.numInPage,
            },
            data: res.data.dataSource,
          });
        } else {
          message.error(res.message);
          callback(null);
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 获取交收列表
    *getList({ payload, callback }, { call }) {
      const res = yield call(api.bookkeepingMnt.getList, payload);
      const columns = [
        {
          title: '日期',
          dataIndex: 'createdTs',
          key: 'createdTs',
          width: 120,
          render: (val) => <span>{moment(val).format('YYYY-MM-DD')}</span>,
        },

        {
          title: '产品名称',
          dataIndex: 'productName',
          key: 'productName',
          width: 180,
        },
        {
          title: '组合名称',
          dataIndex: 'portfolioInfoName',
          key: 'portfolioInfoName',
          width: 180,
        },
        {
          title: '证券代码',
          dataIndex: 'tradingCode',
          key: 'tradingCode',
          width: 150,
        },
        {
          title: '证券名称',
          dataIndex: 'tradingName',
          key: 'tradingName',
          width: 160,
        },
        {
          title: '交易市场',
          dataIndex: 'securityExchange',
          key: 'securityExchange',
          width: 120,
          render: (val, record) => {
            const trade = typeOfTradeX(record);
            if (trade) {
              const findvalue = config.filter((item) => {
                if (record.type == '19') {
                  // 港股通
                  return item.value == trade.exchangecode;
                }
                return item.value == trade.exchangeCode;
              });
              if (findvalue && findvalue.length > 0) {
                return findvalue[0].title;
              }
              return '--';
            }
          },
        },
        {
          title: '资产类型',
          dataIndex: 'type',
          key: 'type',
          width: 140,
          render: (val, record) => {
            const findType = typeConfig.filter(
              (item) => item.value == (record.type == 24 ? 23 : record.type), // 业务类型23 24为同一个
              // eslint-disable-next-line function-paren-newline
            );
            if (findType && findType.length > 0) {
              return findType[0].title;
            }
            return '--';
          },
        },
        {
          title: '投资类型',
          dataIndex: 'investmentType',
          key: 'investmentType',
          width: 80,
        },
        {
          title: '交易方向',
          dataIndex: 'orderSide',
          key: 'orderSide',
          width: 80,
          render: (val, record) => {
            // 根据业务类型，翻译交易方向
            const trade = typeOfTradeX(record);
            if (trade) {
              const findtypes = typeConfig.filter(
                (item) => item.value == (record.type == 24 ? 23 : record.type == 33 ? 32 : record.type), // 业务类型23 24为同一个  32,33为同一个
                // eslint-disable-next-line function-paren-newline
              );
              if (findtypes && findtypes.length > 0) {
                const findorderSide = findtypes[0].tradingDirect.filter((item) => item.value == findKeyword(trade, record, 'orderSide'));
                if (findorderSide && findorderSide.length > 0) {
                  if (record.type == '3') {
                    // 当业务类型为 3-协商成交，那么交易方向特殊处理成“方向-委托类型”
                    const delegationType = delegationTypeData.filter((item) => item.value == trade.delegationType);
                    return `${findorderSide[0].title}-${delegationType[0]?.title}`;
                  }
                  return findorderSide[0].title;
                }
                return '--';
              }
              return '--';
            }
          },
        },
        {
          title: '交易数量',
          dataIndex: 'tAmount',
          key: 'tAmount',
          type: 'number',
          width: 110,
          render: (val, record) => {
            const trade = typeOfTradeX(record);
            if (record.type == '13') {
              if (Array.isArray(trade.pledgeVo) && trade.pledgeVo.length != 0 && trade.pledgeVo[0].transactionAmount) {
                return +trade.pledgeVo[0].transactionAmount / 100;
              }
              return '--';
            }
            return findKeyword(trade, record, 'tAmount');
          },
        },
        {
          title: '价格（净价）',
          dataIndex: 'price',
          key: 'price',
          type: 'money',
          width: 110,
          render: (val, record) => {
            const trade = typeOfTradeX(record);
            if (record.type == '5') {
              // if(record.instructionStatus=='7'||record.instructionStatus=='8'){
              //   if(trade.applyNum==null){
              //     return '--'
              //   }
              //   return +trade.applyAmount/trade.applyNum
              // }else{
              //   return '--'
              // }
              if (trade.applyNum == null || trade.applyNum == undefined||trade.applyAmount==null) {
                return '--';
              }
              return accounting.formatNumber(Number(+trade.applyAmount / trade.applyNum), 4);
            }
            if (record.type == '19') {
              // 港股通
              const text = findKeyword(trade, record, 'price', 'moneys');
              if (text == '--') {
                return '--';
              }
              return `${text}(HKD)`;
            }
            return findKeyword(trade, record, 'price', 'moneys');
          },
        },
        {
          title: '价格（全价）',
          dataIndex: 'amount',
          key: 'amount',
          type: 'money',
          className: 'column-right',
          width: 110,
          render: (val, record) => {
            const trade = typeOfTradeX(record);
            if (findKeyword(trade, record, 'amount', 'moneys')) {
              return findKeyword(trade, record, 'amount', 'moneys');
            }
            if(findKeyword(trade, record, 'amount', 'moneys')=='') return '';//展示为空白
            return fixedNum(val);
          },
        },
        {
          title: '利率（%）',
          dataIndex: 'repoRate',
          key: 'repoRate',
          type: 'rate',
          className: 'column-right',
          width: 110,
          render: (val, record) => {
            const trade = typeOfTradeX(record);
            if (trade) {
              if (record.type == '7') {
                const num = findKeyword(trade, record, 'orderSide');
                if (num == 3 || num == 4) {
                  return '--';
                }
              }
              if (record.type === '8') {
                if (record.trade8.orderSize == 'F') {
                  return findKeyword(trade, record, 'repoRateF', 'rate');
                } else if (record.trade8.orderSize == 'i') {
                  return findKeyword(trade, record, 'repoRateI', 'rate');
                }
                return '--';
              }
            }
            return findKeyword(trade, record, 'repoRate', 'rate');
          },
        },
        {
          title: '交易金额',
          dataIndex: 'settlementAmount',
          key: 'settlementAmount',
          type: 'money',
          className: 'column-right',
          width: 110,
          render: (val, record) => {
            const trade = typeOfTradeX(record);
            if (trade) {
              if (record.type === '8') {
                if (record.trade8.orderSize == 'F') {
                  return findKeyword(trade, record, 'settlementAmountF', 'rate');
                } else if (record.trade8.orderSize == 'i' || record.trade8.orderSize == 'calc') {
                  return findKeyword(trade, record, 'settlementAmountI', 'rate');
                }
                return '--';
              }
              if (record.type == '19') {
                // 港股通
                const text = findKeyword(trade, record, 'settlementAmount', 'money');
                if (text == '--') {
                  return '--';
                }
                return `${text}(HKD)`;
              }
            }
            return findKeyword(trade, record, 'settlementAmount', 'money');
          },
        },
        {
          title: '清算速度',
          dataIndex: 'settlementSpeed',
          key: 'settlementSpeed',
          width: 90,
          render: (val, record) => {
            const trade = typeOfTradeX(record);
            if (trade) {
              const newSettlementSpeed = findKeyword(trade, record, 'settlementSpeed');
              if (newSettlementSpeed == '1') {
                return 'T+0';
              }
              if (newSettlementSpeed == '2') {
                return 'T+1';
              }
              if (newSettlementSpeed == '0') {
                return 'T+0';
              }
            }
          },
        },
        {
          title: '交易对手',
          dataIndex: 'externalName',
          key: 'externalName',
          width: 90,
          render: (val, record) => {
            const trade = typeOfTradeX(record);
            if (trade) {
              if (['1', '2', '3', '4', '16', '25', '32', '33'].includes(record.type)) {
                if (record.externalName === null || record.externalName === undefined) {
                  return '--';
                }
                return record.externalName;
              }
              return findKeyword(trade, record, 'externalName');
            }
          },
        },
        {
          title: '下达人',
          dataIndex: 'userName',
          key: 'userName',
          width: 140,
        },
        {
          title: '来源',
          dataIndex: 'source',
          key: 'source',
          width: 80,
          // 0 簿记, 1导入
          render: (_) => (_ == 0 ? '簿记' : _ == 1 ? '导入' : '--'),
        },
      ];
      if (res && res.success) {
        res.data &&
          res.data.map((item) => {
            if (item.type == '17') {
              // 中签状态 拿到外层 方便使用tableC操作按钮
              item.bondOffStatus = item.trade17.status;
            }
          });
        callback({
          pageInfo: {
            total: res.total,
            currentPage: res.current,
            pageSize: res.pageSize,
          },
          dataSource: res.data,
          columns,
        });
      }
    },
    // 删除
    *delTrade({ payload, callback }, { call }) {
      const response = yield call(api.bookkeepingMnt.delTrade, payload);
      if (response && response.success) {
        callback('success');
        message.success('删除成功');
      } else {
        callback('fail');
        message.error(response.message || '删除失败!');
      }
    },

    *uploadFile({ payload, callback }, { call }) {
      const response = yield call(api.bookkeepingMnt.uploadFile, payload);
      callback(response);
    },
  },
  reducers: {
    updateData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {},
};
